<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PMO 项目管理</title>
    <!-- 引入 Element Plus 的样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css" />
    <style>
        body { font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif; }
        #app { padding: 20px; }
        .toolbar { margin-bottom: 20px; }
        .form-section-header { font-size: 16px; font-weight: bold; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #dcdfe6; padding-bottom: 5px; }
        .form-row { display: flex; gap: 20px; }
        .nested-form-item { margin-bottom: 15px; padding: 10px; border: 1px dashed #dcdfe6; border-radius: 4px; }
    </style>
</head>
<body>

<div id="app">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
        <el-button type="primary" @click="handleCreate">新增项目</el-button>
    </div>

    <!-- 项目数据表格 -->
    <el-table :data="projects" border stripe v-loading="loading" :header-cell-style="{ background: '#5a6268', color: '#ffffff' }">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="项目名称" width="250"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="250"></el-table-column>
        <el-table-column prop="projectType" label="类型" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="120"></el-table-column>
        <el-table-column prop="agreedGoLiveDate" label="计划上线" width="150">
             <template #default="{ row }">
                <span>{{ formatDisplayDate(row.agreedGoLiveDate) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
                <el-button type="warning" size="small" @click="handleEdit(row)">修改</el-button>
                <el-button type="danger" size="small" @click="confirmDelete(row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 新增/修改/查看项目的弹窗 -->
    <el-dialog :title="formTitle" v-model="dialogVisible" width="75%" :close-on-click-modal="false">
        <el-form :model="projectForm" label-width="140px" ref="projectFormRef" :disabled="isReadonly">
            
            <!-- 1. 客户与项目核心信息 -->
            <div class="form-section-header">客户与项目核心信息</div>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="项目名称">
                        <el-input v-model="projectForm.name" placeholder="请输入项目名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="项目类型">
                        <el-input v-model="projectForm.projectType" placeholder="例如: 正式立项, 技改立项"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="客户名称">
                        <el-input v-model="projectForm.customer.name" placeholder="请输入客户全称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                     <el-form-item label="客户分类">
                        <el-select v-model="projectForm.customer.category" placeholder="请选择客户分类">
                            <el-option label="新客户" value="新客户"></el-option>
                            <el-option label="老客户" value="老客户"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 2. 立项详情 -->
            <div class="form-section-header">立项详情</div>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="目前所处阶段">
                        <el-input v-model="projectForm.initiationStage"></el-input>
                    </el-form-item>
                </el-col>
                 <el-col :span="12">
                    <el-form-item label="预立项原因">
                        <el-input v-model="projectForm.initiationReason" type="textarea" :rows="1"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="计划签约日期">
                        <el-date-picker v-model="projectForm.plannedSigningDate" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="希望开立项会时间">
                        <el-date-picker v-model="projectForm.desiredMeetingTime" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
             <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="约定入场时间">
                        <el-date-picker v-model="projectForm.agreedStartDate" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="约定上线时间">
                        <el-date-picker v-model="projectForm.agreedGoLiveDate" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="售前评估总人天">
                        <el-input-number v-model="projectForm.presalesEstimatedManDays" :precision="2" :step="1"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="本次立项人天">
                         <el-input-number v-model="projectForm.initiationManDays" :precision="2" :step="1"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 3. 人员信息 -->
            <div class="form-section-header">相关人员 (输入姓名)</div>
             <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="销售人员">
                        <el-input v-model="projectForm.salesName" placeholder="输入姓名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="主售前人员">
                         <el-input v-model="projectForm.mainPresalesName" placeholder="输入姓名"></el-input>
                    </el-form-item>
                </el-col>
                 <el-col :span="8">
                    <el-form-item label="辅售前人员">
                         <el-input v-model="projectForm.auxPresalesName" placeholder="输入姓名"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 4. 客户联系人 -->
            <div class="form-section-header">客户联系人</div>
            <div v-for="(contact, index) in projectForm.clientContacts" :key="index" class="nested-form-item">
                 <el-row :gutter="20">
                    <el-col :span="7">
                        <el-form-item label="姓名"><el-input v-model="contact.name"></el-input></el-form-item>
                    </el-col>
                    <el-col :span="7">
                       <el-form-item label="职位"><el-input v-model="contact.position"></el-input></el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="电话"><el-input v-model="contact.phone"></el-input></el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-button type="danger" @click="removeClientContact(index)">移除</el-button>
                    </el-col>
                </el-row>
            </div>
            <el-form-item>
                <el-button type="success" @click="addClientContact">添加客户联系人</el-button>
            </el-form-item>

            <!-- 5. 工作包 -->
            <div class="form-section-header">工作包内容</div>
            <div v-for="(wp, index) in projectForm.workPackages" :key="index" class="nested-form-item">
                 <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="工作包类型">
                            <el-select v-model="wp.packageType">
                                <el-option label="实施内容" value="实施内容"></el-option>
                                <el-option label="开发内容" value="开发内容"></el-option>
                                <el-option label="数据建设内容" value="数据建设内容"></el-option>
                                <el-option label="运维服务内容" value="运维服务内容"></el-option>
                                <el-option label="自研业务内容" value="自研业务内容"></el-option>
                                <el-option label="第三方内容" value="第三方内容"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                     <el-col :span="7">
                        <el-form-item label="内容描述">
                            <el-input v-model="wp.description"></el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="6">
                        <el-form-item 
                            :label="`工作量(人天)`" 
                            :prop="'workPackages.' + index + '.estimatedWorkload'"
                            :rules="{ required: true, message: '工作量不能为空', trigger: 'blur' }">
                            <el-input-number v-model="wp.estimatedWorkload" :precision="2" :step="1" style="width:100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                     <el-col :span="5">
                        <el-form-item 
                            :label="`评估人`"
                            :prop="'workPackages.' + index + '.estimatorName'">
                            <el-select v-model="wp.estimatorName" placeholder="选择评估人" filterable style="width: 100%;">
                                <el-option v-for="emp in employees" :key="emp.id" :label="emp.name" :value="emp.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-button type="danger" @click="removeWorkPackage(index)">移除</el-button>
                    </el-col>
                </el-row>
            </div>
            <el-form-item>
                <el-button type="success" @click="addWorkPackage">添加工作包</el-button>
            </el-form-item>

            <!-- 6. 其他信息 -->
            <div class="form-section-header">其他信息</div>
             <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="项目前期关联事项">
                        <el-input v-model="projectForm.preProjectMatters" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
                 <el-col :span="12">
                    <el-form-item label="售前给客户的特别承诺">
                        <el-input v-model="projectForm.preProjectCommitments" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="风险信息">
                        <el-input v-model="projectForm.riskInfo" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
                 <el-col :span="12">
                    <el-form-item label="备注">
                        <el-input v-model="projectForm.remarks" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button v-if="!isReadonly" @click="dialogVisible = false">取消</el-button>
                <el-button v-if="!isReadonly" type="primary" @click="submitForm">提交</el-button>
                <el-button v-if="isReadonly" type="primary" @click="dialogVisible = false">关闭</el-button>
            </span>
        </template>
    </el-dialog>
</div>

<!-- 引入 Vue, Element Plus 和 Axios 的 JS -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
    const { createApp, ref, reactive, onMounted } = Vue;
    const { ElMessage, ElMessageBox } = ElementPlus;

    createApp({
        setup() {
            // --- 状态管理 ---
            const loading = ref(false);
            const projects = ref([]); // 表格数据
            const employees = ref([]); // 新增：用于存储员工列表
            const dialogVisible = ref(false); // 弹窗可见性
            const isReadonly = ref(false); // 新增：表单是否只读
            const formTitle = ref(''); // 弹窗标题
            
            // 定义一个空的表单结构，包含所有字段
            const createEmptyForm = () => ({
                id: null,
                name: '', // projects.name
                projectType: '正式立项',
                initiationStage: '开发阶段',
                initiationReason: '',
                plannedSigningDate: null,
                desiredMeetingTime: null,
                agreedStartDate: null,
                agreedGoLiveDate: null,
                presalesEstimatedManDays: 0,
                initiationManDays: 0,
                preProjectMatters: '',
                preProjectCommitments: '',
                riskInfo: '',
                remarks: '',
                status: '立项中',
                
                // 关联对象和列表
                customer: {
                    name: '',
                    category: '新客户'
                },
                salesName: '',
                mainPresalesName: '',
                auxPresalesName: '',
                clientContacts: [],
                workPackages: []
            });

            const projectForm = reactive(createEmptyForm());

            //用于连接后端 ---
            const apiClient = axios.create({
                baseURL: 'http://localhost:8080', // 后端地址
                headers: { 'Content-Type': 'application/json' }
            });

            // --- 方法 ---

            // 1. 查询所有项目
            const fetchProjects = async () => {
                loading.value = true;
                try {
                    // 【GET /api/select】
                    const response = await apiClient.get('/api/select');
                    projects.value = response.data; 

                } catch (error) {
                    ElMessage.error('获取项目列表失败！');
                    console.error(error);
                } finally {
                    loading.value = false;
                }
            };

            // 新增：获取员工列表
            const fetchEmployees = async () => {
                 try {
                    // 【GET /api/employees】 - 假设的后端接口
                    const response = await apiClient.get('/api/employees');
                    employees.value = response.data;
                } catch (error) {
                    ElMessage.error('获取员工列表失败！');
                    console.error(error);
                }
            };

            // 新增一个格式化日期的方法
            const formatDisplayDate = (dateString) => {
                if (!dateString) return '';
                // 只截取日期部分 YYYY-MM-DD
                return dateString.split('T')[0];
            };

            // 2. 处理新增按钮点击
            const handleCreate = () => {
                Object.assign(projectForm, createEmptyForm()); // 重置表单
                isReadonly.value = false; // 确保不是只读模式
                formTitle.value = '新增项目';
                dialogVisible.value = true;
            };

            // 新增：处理查看按钮点击
            const handleView = async (row) => {
                formTitle.value = '查看项目详情';
                isReadonly.value = true;
                dialogVisible.value = true;
                loading.value = true;

                try {
                    const response = await apiClient.get(`/api/project/${row.id}`);
                    const projectData = response.data;
                    Object.assign(projectForm, createEmptyForm(), projectData);
                } catch (error) {
                    ElMessage.error('获取项目详情失败！');
                    console.error(error);
                    dialogVisible.value = false;
                } finally {
                    loading.value = false;
                }
            };

            // 3. 处理修改按钮点击
            const handleEdit = async (row) => {
                formTitle.value = '修改项目';
                isReadonly.value = false; // 确保不是只读模式
                dialogVisible.value = true;
                loading.value = true; // 显示加载状态

                try {
                    // 调用新的API来获取完整的项目详情
                    const response = await apiClient.get(`/api/project/${row.id}`);
                    const projectData = response.data;

                    // 清空并填充表单
                    Object.assign(projectForm, createEmptyForm(), projectData);

                } catch (error) {
                    ElMessage.error('获取项目详情失败！请检查后端接口是否实现。');
                    console.error(error);
                    dialogVisible.value = false; // 获取失败则关闭弹窗
                } finally {
                    loading.value = false; // 关闭加载状态
                }
            };

            // 4. 处理删除按钮点击 - 修改为调用新的确认函数
            const confirmDelete = (row) => {
                ElMessageBox.confirm(
                    `您正在操作项目 "${row.name}"。请选择删除方式：`,
                    '删除确认',
                    {
                        distinguishCancelAndClose: true,
                        confirmButtonText: '永久删除', // 物理删除
                        cancelButtonText: '删除', // 逻辑删除
                        type: 'warning',
                    }
                )
                .then(() => {
                    // 用户点击了“彻底删除”
                    handleDelete(row.id, 'physical');
                })
                .catch((action) => {
                    
                    if (action === 'cancel') {
                        handleDelete(row.id, 'logical');
                    } else {
                        ElMessage.info('操作已取消');
                    }
                });
            };

            // 5. 真正的删除执行函数
            const handleDelete = async (id, type) => {
                const typeText = type === 'physical' ? '永久删除' : '删除';
                try {
                    await apiClient.post('/api/delete', { id: id, type: type });
                    ElMessage.success(`${typeText}成功！`);
                    fetchProjects(); // 
                } catch (error) {
                    ElMessage.error(`${typeText}失败！`);
                    console.error(error);
                }
            };
            
            // 6. 提交表单
            const submitForm = async () => {
                try {
                    if (projectForm.id) {
                        // 修改逻辑
                        // 【POST /api/update】
                        await apiClient.post('/api/update', projectForm);
                        ElMessage.success('修改成功！');
                    } else {
                        // 新增逻辑
                        // 【POST /api/insert/】
                        await apiClient.post('/api/insert', projectForm);
                        ElMessage.success('新增成功！');
                    }
                    dialogVisible.value = false;
                    fetchProjects(); // 刷新列表
                } catch(error) {
                    ElMessage.error('操作失败！');
                    console.error(error);
                }
            };

            // --- 动态表单方法 ---
            const addWorkPackage = () => {
                projectForm.workPackages.push({ packageType: '实施内容', description: '', estimatedWorkload: 0, estimatorName: '' });
            };
            const removeWorkPackage = (index) => {
                projectForm.workPackages.splice(index, 1);
            };

            const addClientContact = () => {
                projectForm.clientContacts.push({ name: '', position: '', phone: '' });
            };
            const removeClientContact = (index) => {
                projectForm.clientContacts.splice(index, 1);
            };

            // --- 生命周期钩子 ---
            onMounted(() => {
                fetchProjects();
                fetchEmployees(); // 获取员工列表
            });

            return {
                loading,
                projects,
                employees,
                dialogVisible,
                isReadonly, // 暴露给模板
                formTitle,
                projectForm,
                formatDisplayDate,
                handleCreate,
                handleView, // 暴露新方法
                handleEdit,
                confirmDelete, // 暴露新的确认函数
                handleDelete,
                submitForm,
                addWorkPackage,
                removeWorkPackage,
                addClientContact,
                removeClientContact
            };
        }
    }).use(ElementPlus).mount('#app');
</script>

</body>
</html> 